<template>
  <div class="login-container">
    <!-- 登录系统标题 -->
    <div class="login-page">
      <van-nav-bar title="登录系统" />
    </div>

    <!-- 新增图片区域 -->
    <div class="logo-container">
      <img src="../assets/tubiao.jpg" alt="logo" />
    </div>

    <!-- 登录表单 -->
    <van-form @submit="handleLogin">
      <van-cell-group inset>
        <van-field
          v-model="loginForm.username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[
            { required: true, message: '必填项' },
            { pattern: /^.{4,}$/, message: '用户名长度不能小于4位', trigger: 'onBlur' }
          ]"
        />
        <van-field
          v-model="loginForm.password"
          type="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[
            { required: true, message: '必填项' },
            { pattern: /^.{6,}$/, message: '密码长度不能小于6位', trigger: 'onBlur' }
          ]"
        />
        <!-- 验证码输入框 -->
        <van-field
          v-model="loginForm.captcha"
          label="验证码"
          placeholder="请输入验证码"
          :rules="[
            { required: true, message: '必填项' }
          ]"
        />
        <!-- 验证码图片 + 点击刷新 -->
        <div class="captcha-wrap" @click="refreshCaptcha">
          <canvas
            ref="captchaCanvas"
            width="100"
            height="40"
            class="captcha-canvas"
          ></canvas>
        </div>
      </van-cell-group>

      <div class="form-actions">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="isSubmitting"
          :disabled="!agreed"
        >
          立即登录
        </van-button>
        <div class="link-group">
          <router-link to="" @click="showForget">忘记密码</router-link>
          <router-link to="register">注册账号</router-link>
        </div>
      </div>

      <!-- 协议勾选区域 -->
      <div class="agreement">
        <van-checkbox v-model="agreed" shape="square" class="agreement-checkbox">
          已阅读并同意《服务协议》和《隐私政策》
        </van-checkbox>
        <span
          v-if="!agreed && showAgreementHint"
          class="agreement-hint"
        >
          请阅读并同意相关协议才能登录
        </span>
      </div>
    </van-form>
  </div>
</template>

<script setup name="login">
import { ref, onMounted, nextTick } from 'vue'
import { showToast, Checkbox } from 'vant'
import { useRouter } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'

const VanCheckbox = Checkbox
const userInfoStore = useUserInfoStore()
const router = useRouter()

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
  captcha: '' // 验证码
})

// 验证码相关
const captchaCanvas = ref(null) // canvas 实例
const realCaptcha = ref('') // 真实验证码（前端生成，用于校验）
const isSubmitting = ref(false)
const agreed = ref(false)
const showAgreementHint = ref(false)

// 生成随机验证码（纯前端模拟）
const generateCaptcha = () => {
  const canvas = captchaCanvas.value
  const ctx = canvas.getContext('2d')
  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 随机生成 4 位验证码
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let captcha = ''
  for (let i = 0; i < 4; i++) {
    captcha += chars[Math.floor(Math.random() * chars.length)]
  }
  realCaptcha.value = captcha

  // 绘制验证码到 canvas
  ctx.font = '20px Arial'
  ctx.fillStyle = '#333'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  // 随机干扰线
  for (let i = 0; i < 5; i++) {
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.strokeStyle = '#ccc'
    ctx.stroke()
  }
  // 绘制文字
  ctx.fillText(captcha, canvas.width / 2, canvas.height / 2)
}

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha()
}

// 处理登录
const handleLogin = async () => {
  if (!agreed.value) {
    showAgreementHint.value = true
    setTimeout(() => {
      showAgreementHint.value = false
    }, 3000)
    return
  }

  showAgreementHint.value = false

  // 校验验证码
  if (loginForm.value.captcha.toLowerCase()!== realCaptcha.value.toLowerCase()) {
    showToast('验证码错误，请重新输入')
    // 刷新验证码
    refreshCaptcha()
    return
  }

  if (!loginForm.value.username ||!loginForm.value.password) {
    showToast('请填写用户名和密码')
    return
  }

  isSubmitting.value = true

  try {
    // 这里依然调用 store 登录（实际需结合后端，当前仅演示）
    await userInfoStore.login(loginForm.value)
    await userInfoStore.getInfo()
    
    showToast('登录成功')
    router.push({ name: 'homepage' })
  } catch (e) {
    console.log(e.message)
    showToast(e.message || '登录失败')
    // 登录失败后刷新验证码
    refreshCaptcha()
  } finally {
    isSubmitting.value = false
  }
}

const showForget = () => {
  showToast('请联系管理员重置密码')
}

onMounted(() => {
  nextTick(() => {
    // 初始化生成验证码
    generateCaptcha()
  })
})
</script>

<style lang='less' scoped>
.login-container {
  padding: 5% 16px 0;
  background-color: #f7f9fc;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-container {
  margin: 40px 0;
  width: 100%;
  display: flex;
  justify-content: center;
  img {
    width: 130px; 
    height: auto;
  }
}

.form-actions {
  margin: 24px 16px;
  .link-group {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    a {
      color: #0070c9;
      text-decoration: none;
    }
  }
}

::v-deep(.van-field_control) {
  border: 1px solid #ebedf0 !important;
  border-radius: 8px;
  padding: 12px;
  background: #fbfbfc;
}

.agreement {
  text-align: center;
  margin: 30px 16px 0;
  font-size: 12px;
  color: #666;
  display: flex;
  justify-content: center;
  align-items: center;
}

.agreement-checkbox {
  display: flex;
  align-items: center;
  ::v-deep(.van-checkbox) {
    margin-right: 6px;
  }
  ::v-deep(.van-checkbox__label) {
    color: #666;
    line-height: 1;
  }
}

.agreement-hint {
  display: block;
  margin-top: 5px;
  color: #ff4d4f;
  font-size: 12px;
  width: 100%;
  text-align: center;
}

::v-deep(.van-cell-group) {
  width: 90%;
  margin: 0 auto;
}

van-form {
  width: 100%;
}

.login-page {
  width: 100%;
}

/* 验证码样式 */
.captcha-wrap {
  margin-top: 10px;
  text-align: center;
  cursor: pointer;
  .captcha-canvas {
    vertical-align: middle;
  }
}
</style>